import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Box,
  Paper,
  Typography,
  TextField,
  Button,
  Grid,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  FormControlLabel,
  Switch,
  Card,
  CardContent,
  CardHeader,
  Divider,
  Chip,
  Checkbox,
  FormGroup,
  Alert,
  CircularProgress,
  Breadcrumbs,
  Link
} from '@mui/material';
import {
  Save as SaveIcon,
  Cancel as CancelIcon,
  ArrowBack as ArrowBackIcon,
  Security as SecurityIcon
} from '@mui/icons-material';
import { useForm, Controller } from 'react-hook-form';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { PageHeader } from '@/components/common/PageHeader';
import { roleService } from '@/services/roleService';
import { permissionService } from '@/services/permissionService';
import type { CreateRoleRequest, Permission } from '@/types';

interface RoleFormData {
  name: string;
  code: string;
  description?: string;
  status: 'active' | 'inactive';
  isDefault: boolean;
  isSystem: boolean;
  permissions: string[];
}

const RoleCreatePage: React.FC = () => {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const [selectedPermissions, setSelectedPermissions] = useState<string[]>([]);

  const {
    control,
    handleSubmit,
    watch,
    setValue,
    formState: { errors, isValid }
  } = useForm<RoleFormData>({
    defaultValues: {
      name: '',
      code: '',
      description: '',
      status: 'active',
      isDefault: false,
      isSystem: false,
      permissions: []
    },
    mode: 'onChange'
  });

  // 获取所有权限
  const { data: permissions = [], isLoading: permissionsLoading } = useQuery({
    queryKey: ['permissions'],
    queryFn: () => permissionService.getPermissions({})
  });

  // 创建角色
  const createRoleMutation = useMutation({
    mutationFn: (data: CreateRoleRequest) => roleService.createRole(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['roles'] });
      navigate('/roles');
    }
  });

  const onSubmit = (data: RoleFormData) => {
    const createData: CreateRoleRequest = {
      ...data,
      permissions: selectedPermissions
    };
    createRoleMutation.mutate(createData);
  };

  const handlePermissionChange = (permissionId: string, checked: boolean) => {
    if (checked) {
      setSelectedPermissions(prev => [...prev, permissionId]);
    } else {
      setSelectedPermissions(prev => prev.filter(id => id !== permissionId));
    }
  };

  const handleSelectAllPermissions = (checked: boolean) => {
    if (checked) {
      setSelectedPermissions(permissions.map((p: Permission) => p.id));
    } else {
      setSelectedPermissions([]);
    }
  };

  // 根据名称自动生成角色代码
  const roleName = watch('name');
  useEffect(() => {
    if (roleName) {
      const code = roleName
        .toLowerCase()
        .replace(/[\s\u4e00-\u9fa5]/g, '_')
        .replace(/[^a-z0-9_]/g, '')
        .replace(/_+/g, '_')
        .replace(/^_|_$/g, '');
      setValue('code', `ROLE_${code.toUpperCase()}`);
    }
  }, [roleName, setValue]);

  // 按模块分组权限
  const groupedPermissions = React.useMemo(() => {
    const groups: Record<string, Permission[]> = {};
    permissions.forEach((permission: Permission) => {
      const module = permission.module || '其他';
      if (!groups[module]) {
        groups[module] = [];
      }
      groups[module].push(permission);
    });
    return groups;
  }, [permissions]);

  if (permissionsLoading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: 400 }}>
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Box sx={{ p: 3 }}>
      {/* 面包屑导航 */}
      <Breadcrumbs sx={{ mb: 2 }}>
        <Link
          component="button"
          variant="body2"
          onClick={() => navigate('/roles')}
          sx={{ textDecoration: 'none', '&:hover': { textDecoration: 'underline' } }}
        >
          角色管理
        </Link>
        <Typography variant="body2" color="text.primary">
          创建角色
        </Typography>
      </Breadcrumbs>

      <PageHeader
        title="创建角色"
        description="创建新的系统角色并分配相应权限"
        action={
          <Button
            startIcon={<ArrowBackIcon />}
            onClick={() => navigate('/roles')}
            variant="outlined"
          >
            返回列表
          </Button>
        }
      />

      <form onSubmit={handleSubmit(onSubmit)}>
        <Grid container spacing={3}>
          {/* 基本信息 */}
          <Grid item xs={12} md={6}>
            <Card>
              <CardHeader
                title="基本信息"
                titleTypographyProps={{ variant: 'h6' }}
              />
              <Divider />
              <CardContent>
                <Grid container spacing={2}>
                  <Grid item xs={12}>
                    <Controller
                      name="name"
                      control={control}
                      rules={{ required: '角色名称不能为空' }}
                      render={({ field }) => (
                        <TextField
                          {...field}
                          label="角色名称"
                          fullWidth
                          error={!!errors.name}
                          helperText={errors.name?.message}
                        />
                      )}
                    />
                  </Grid>
                  <Grid item xs={12}>
                    <Controller
                      name="code"
                      control={control}
                      rules={{ required: '角色代码不能为空' }}
                      render={({ field }) => (
                        <TextField
                          {...field}
                          label="角色代码"
                          fullWidth
                          error={!!errors.code}
                          helperText={errors.code?.message || '系统唯一标识，建议使用大写字母和下划线'}
                        />
                      )}
                    />
                  </Grid>
                  <Grid item xs={12}>
                    <Controller
                      name="description"
                      control={control}
                      render={({ field }) => (
                        <TextField
                          {...field}
                          label="角色描述"
                          fullWidth
                          multiline
                          rows={3}
                          placeholder="描述该角色的职责和用途"
                        />
                      )}
                    />
                  </Grid>
                  <Grid item xs={12}>
                    <Controller
                      name="status"
                      control={control}
                      render={({ field }) => (
                        <FormControl fullWidth>
                          <InputLabel>状态</InputLabel>
                          <Select {...field} label="状态">
                            <MenuItem value="active">启用</MenuItem>
                            <MenuItem value="inactive">禁用</MenuItem>
                          </Select>
                        </FormControl>
                      )}
                    />
                  </Grid>
                  <Grid item xs={12}>
                    <Controller
                      name="isDefault"
                      control={control}
                      render={({ field }) => (
                        <FormControlLabel
                          control={<Switch {...field} checked={field.value} />}
                          label="默认角色"
                        />
                      )}
                    />
                  </Grid>
                  <Grid item xs={12}>
                    <Controller
                      name="isSystem"
                      control={control}
                      render={({ field }) => (
                        <FormControlLabel
                          control={<Switch {...field} checked={field.value} />}
                          label="系统角色"
                        />
                      )}
                    />
                  </Grid>
                </Grid>
              </CardContent>
            </Card>
          </Grid>

          {/* 权限分配 */}
          <Grid item xs={12} md={6}>
            <Card>
              <CardHeader
                title="权限分配"
                titleTypographyProps={{ variant: 'h6' }}
                action={
                  <FormControlLabel
                    control={
                      <Checkbox
                        checked={selectedPermissions.length === permissions.length}
                        indeterminate={
                          selectedPermissions.length > 0 &&
                          selectedPermissions.length < permissions.length
                        }
                        onChange={(e) => handleSelectAllPermissions(e.target.checked)}
                      />
                    }
                    label="全选"
                  />
                }
              />
              <Divider />
              <CardContent sx={{ maxHeight: 500, overflow: 'auto' }}>
                {Object.entries(groupedPermissions).map(([module, modulePermissions]) => (
                  <Box key={module} sx={{ mb: 2 }}>
                    <Typography variant="subtitle2" sx={{ mb: 1, color: 'primary.main' }}>
                      <SecurityIcon sx={{ fontSize: 16, mr: 0.5, verticalAlign: 'middle' }} />
                      {module}
                    </Typography>
                    <FormGroup>
                      {modulePermissions.map((permission: Permission) => (
                        <FormControlLabel
                          key={permission.id}
                          control={
                            <Checkbox
                              checked={selectedPermissions.includes(permission.id)}
                              onChange={(e) => handlePermissionChange(permission.id, e.target.checked)}
                              size="small"
                            />
                          }
                          label={
                            <Box>
                              <Typography variant="body2">{permission.name}</Typography>
                              <Typography variant="caption" color="text.secondary">
                                {permission.description}
                              </Typography>
                            </Box>
                          }
                          sx={{ ml: 1, alignItems: 'flex-start' }}
                        />
                      ))}
                    </FormGroup>
                    <Divider sx={{ mt: 1 }} />
                  </Box>
                ))}
              </CardContent>
            </Card>
          </Grid>

          {/* 已选择的权限概览 */}
          <Grid item xs={12}>
            <Card>
              <CardHeader
                title={`已选择权限 (${selectedPermissions.length})`}
                titleTypographyProps={{ variant: 'h6' }}
              />
              <Divider />
              <CardContent>
                {selectedPermissions.length > 0 ? (
                  <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1 }}>
                    {selectedPermissions.map(permissionId => {
                      const permission = permissions.find((p: Permission) => p.id === permissionId);
                      return (
                        <Chip
                          key={permissionId}
                          label={permission?.name || permissionId}
                          size="small"
                          onDelete={() => handlePermissionChange(permissionId, false)}
                          color="primary"
                          variant="outlined"
                        />
                      );
                    })}
                  </Box>
                ) : (
                  <Alert severity="info">请选择该角色需要的权限</Alert>
                )}
              </CardContent>
            </Card>
          </Grid>

          {/* 操作按钮 */}
          <Grid item xs={12}>
            <Box sx={{ display: 'flex', gap: 2, justifyContent: 'flex-end' }}>
              <Button
                variant="outlined"
                startIcon={<CancelIcon />}
                onClick={() => navigate('/roles')}
              >
                取消
              </Button>
              <Button
                type="submit"
                variant="contained"
                startIcon={<SaveIcon />}
                disabled={!isValid || createRoleMutation.isPending}
              >
                {createRoleMutation.isPending ? '创建中...' : '创建角色'}
              </Button>
            </Box>
          </Grid>
        </Grid>
      </form>
    </Box>
  );
};

export default RoleCreatePage;